package org.dromara.common.security.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.dromara.common.core.utils.ServletUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.dao.business.domain.UserApiRecord;
import org.dromara.dao.business.mapper.UserApiRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;



@Component
public class UserApiInterceptor implements HandlerInterceptor {


    @Autowired
    UserApiRecordMapper userApiRecordMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 确保是方法
        if (handler instanceof HandlerMethod) {
            Long userId = LoginHelper.getAppUserId();
            if (userId == null) {
                return true;
            }



            String ip = ServletUtils.getClientIP();

            UserApiRecord record = new UserApiRecord();
            record.setUserId(userId);
            record.setIp(ip);
            record.setPort("80");
            record.setUrl(request.getRequestURI());
            record.setSessionId(request.getSession().getId());

            userApiRecordMapper.insert(record);
        }
        return true;
    }
}
